package cn.itcast.activiti.servlet.deployment;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.DeploymentBuilder;

import cn.itcast.activiti.common.ProcessEngineUtils;


/**
 * 流程定义部署
 * @author LEE.SIU.WAH
 * @email lixiaohua7@163.com
 * @date 2016年5月6日 下午2:43:15
 * @version 1.0
 */
@WebServlet("/deploy.action")
@MultipartConfig()//servlet3.0文件上传
public class ProcessDefinitionDeployServlet extends HttpServlet{

	private static final long serialVersionUID = -3342556979701484100L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**请求设置编码 */
		request.setCharacterEncoding("utf-8");
		/**接收请求参数 */
		String processName=request.getParameter("processName");
		System.out.println(processName);
		/**获取文件上传对象*/
		Part part=request.getPart("bpmn");
		System.out.println("上传的文件对应类型: "+ part.getContentType());
		System.out.println("上传的文件对应的输入流"+part.getInputStream());
		
		/** 获取上传文件的内容性质 */
		String contentDisposition=part.getHeader("content-disposition");
		/** 获取上传的文件名 */
		String filename=contentDisposition.substring(contentDisposition.lastIndexOf("=")+2, contentDisposition.length()-1);
		System.out.println("文件名为: "+filename);
		
		/** 获取流程引擎 */
		ProcessEngine pe=ProcessEngineUtils.getProcessEngine();
		/** 获取仓储服务 */
		RepositoryService rs=pe.getRepositoryService();
		/** 创建部署构建对象 */
		DeploymentBuilder builder=rs.createDeployment();
		/** 部署名称 */
		builder.name(processName);
		/** 部署分类 */
		builder.category("CZ");
		
		/** 添加流程定义文件对应的输入流 
		 * 第一个参数：流程定义文件的文件名
		 * 第二个参数：流程定义文件对应的输入流
		 * */
		
		builder.addInputStream(filename, part.getInputStream());
		/** 部署 */
		builder.deploy();
		
		
		
		request.getRequestDispatcher("/processDefinitionDeploy.jsp").forward(request, response);
		
		
	}
	
	
	
	
}
